#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    this->setWindowFlag(Qt::FramelessWindowHint);  //去窗口栏
    this->setFixedSize(this->width(),this->height());
     ui->plainTextEdit->setReadOnly(true);
    ui->pushButton_reserch->setFocus();

    iPos=0;                           //标记播放状态为0
    isDrag=false;                          //进度条是否被拖动
    docTextObj=new QTextDocument;     //处理富文本内容

    //初始化networkAccessManager
    networkAccessManager=new QNetworkAccessManager(this);

    //初始化多媒体
    playerObject=new QMediaPlayer(this);
    playerlist=new QMediaPlaylist(this);
    ui->label_soundWave->setVisible(false);
    movie1=new QMovie(":/images/soundWave.gif",QByteArray(),this);

    //设置播放列表
    playerObject->setMedia(playerlist);

    //设置播放模式
    playerlist->setPlaybackMode(QMediaPlaylist::Loop);

    //信号与槽
    connect(playerObject,&QMediaPlayer::positionChanged,this,&MainWindow::timeChangeFunc);
    connect(playerObject,&QMediaPlayer::durationChanged,this,&MainWindow::handleProgressChangeFunc);
    connect(playerObject,&QMediaPlayer::positionChanged,this,&MainWindow::handlePositionChangeFunc);

    connect(networkAccessManager,&QNetworkAccessManager::finished,this,&MainWindow::handleDateBackFunc);

}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::handleDateBackFunc(QNetworkReply *reply)    //信息返回
{
    // 读取网络回馈数据
       byteSearchInfo=reply->readAll();

       QJsonParseError JSonPError; // 定义错误信息对象

       // 将json文本转换为json文件对象
       QJsonDocument JSonDoc_RecvData=QJsonDocument::fromJson(byteSearchInfo,&JSonPError);
       if(JSonPError.error != QJsonParseError::NoError) // 判断是否符合规则
       {
           QMessageBox::critical(this,"Prompt","提示：搜索歌曲获取json格式错误",QMessageBox::Yes);
           return;
       }

       // QJsonObject使用函数object()
       QJsonObject TotalJsonOjbect=JSonDoc_RecvData.object();
       // 列出json里面所有的key
       QStringList strKeys=TotalJsonOjbect.keys();

       if(strKeys.contains("result")) // 有数据信息
       {
           // 将带有result的数据内容提取之后转换为对象
           QJsonObject resultobject=TotalJsonOjbect["result"].toObject();

           // 存储所有keys
           QStringList strResultKeys=resultobject.keys();

           // 如果keys是songs，证明搜索到对应的歌曲
           if(strResultKeys.contains("songs"))
           {
               QJsonArray array = resultobject["songs"].toArray();

               // 通过for循环查找歌曲当中的字段信息
               for(auto isong:array)
               {
                   QJsonObject jsonobect1=isong.toObject();

                   // 获取歌曲ID 歌名 歌手
                   musicId=jsonobect1["id"].toInt();
                   strMusicName=jsonobect1["name"].toString();

                   QStringList strkeys=jsonobect1.keys();

                   if(strkeys.contains("artists"))
                   {
                       QJsonArray artistsjsonarray=jsonobect1["artists"].toArray();
                       for(auto js:artistsjsonarray)
                       {
                           QJsonObject jsonobject2=js.toObject();
                           strSingerName=jsonobject2["name"].toString();
                       }
                   }


               }
           }
       }

       QString strURL;

       strURL=QString("https://music.163.com/song/media/outer/url?id=%0").arg(musicId);

       // 检查链接是否有效
       QNetworkRequest request;
       request.setUrl(QUrl(strURL));
       QNetworkReply *testReply = networkAccessManager->head(request);
       if (testReply->error() != QNetworkReply::NoError) {
           QMessageBox::critical(this, "Prompt", "提示：播放链接无效", QMessageBox::Yes);
           testReply->deleteLater();
       }
       else
       {
           QMessageBox::critical(this, "Prompt", "提示：链接无效", QMessageBox::Yes);
       }

       playerlist->addMedia(QUrl(strURL));

       ui->plainTextEdit->appendPlainText(strMusicName+"-"+strSingerName);
}

void MainWindow::timeChangeFunc(qint64 currentTime)    //处理label时间变化
{
    int m_time=currentTime/1000/60;
    int s_time=currentTime/1000%60;

    totalTime=playerObject->duration();
    int m_totaltime=totalTime/1000/60;
    int s_totaltime=totalTime/1000%60;

    QString strTime=QString("%1:%2/%3:%4").arg(m_time,2,10,QChar('0')).
            arg(s_time,2,10,QChar('0')).arg(m_totaltime,2,10,QChar('0')).arg(s_totaltime,2,10,QChar('0'));

    ui->label_time->setText(strTime);
}


void MainWindow::handleProgressChangeFunc(qint64 maxduration)   //进度条变化  ,传入的是总时间
{
    ui->horizontalSlider_progress->setMaximum(maxduration);

}

void MainWindow::handlePositionChangeFunc(qint64 position)   //拖动进度条变化
{
      if(ui->horizontalSlider_progress->isSliderDown())
          return;

      ui->horizontalSlider_progress->setSliderPosition(position);

}
void MainWindow::on_pushButton_minShow_clicked()
{
    showMinimized();
}

void MainWindow::on_pushButton_exit_clicked()
{
    close();
}

//窗口移动
void MainWindow::mousePressEvent(QMouseEvent* event)
{
    if(event->button()==Qt::LeftButton)
    {
        m_MouseDrag=true;
        mouseStartPoint=event->globalPos();

        windowStartPoint=this->frameGeometry().topLeft();
    }
}
void MainWindow::mouseMoveEvent(QMouseEvent* event)
{
    if(m_MouseDrag)
    {
        //获取鼠标移动的距离
        m_distance=event->globalPos()-mouseStartPoint;
        //根据鼠标移动的距离移动窗口
        this->move(windowStartPoint+m_distance);
    }
}
void MainWindow::mouseReleaseEvent(QMouseEvent* event)
{
    if(event->button()==Qt::LeftButton)
    {
        m_MouseDrag=false;
    }
}

//绘制背景
void MainWindow::paintEvent(QPaintEvent *)
{
    QPainter painter(this);
    painter.drawPixmap(0,0,width(),height(),QPixmap(":/images/background.JPG"));
}
//加载本地MP3
void MainWindow::on_pushButton_file_clicked()
{
    QStringList mp3_list=QFileDialog::getOpenFileNames(this,"请选择MP3格式",QDir::homePath(),"MP3 文件 (*.mp3)");

    if(mp3_list.count()<1)
            return;

    for(auto mp3:mp3_list)
    {
        playerlist->addMedia(QUrl::fromLocalFile(mp3));

        QFileInfo info(mp3);

        ui->plainTextEdit->appendPlainText(info.fileName());
    }


}

void MainWindow::startGifFunc()                 //播放音浪
{

    if(movie1->isValid())
    {
        ui->label_soundWave->setMovie(movie1);
        connect(movie1,&QMovie::finished,movie1,&QMovie::start);
    }
    ui->label_soundWave->setVisible(true);
    movie1->start();
}

void MainWindow::on_pushButton_start_stop_clicked()         //播放歌曲
{

    if(playerlist->mediaCount()==0)
    {
        QMessageBox::information(this,"tip","请先搜索或加载歌曲");
        return;
    }

    if(iPos==0)  //刚开始播放
    {
        QPixmap pixmap(":/images/start.png");
        ui->pushButton_start_stop->setIcon(QIcon(pixmap));
        playerObject->play();

        startGifFunc();      //
        iPos=1;
    }
    else if(iPos==1)  //表示暂停
    {
        QPixmap pixmap(":/images/stop.png");
        ui->pushButton_start_stop->setIcon(QIcon(pixmap));
        playerObject->pause();
        movie1->stop();
        iPos=2;
    }
    else if(iPos==2)  //表示正常播放
    {
        QPixmap pixmap(":/images/start.png");
        ui->pushButton_start_stop->setIcon(QIcon(pixmap));
        playerObject->play();
        startGifFunc();
        iPos=1;
    }


}

void MainWindow::on_pushButton_font_clicked()       //上一曲
{
    int index=playerlist->currentIndex();
    int sum=playerlist->mediaCount();
    if(index>0)
    {
        index--;
    }
    else
    {
        index=sum-1;
    }
    playerlist->setCurrentIndex(index);
    playerObject->play();
}

void MainWindow::on_pushButton_next_clicked()           //下一曲
{
       int index=playerlist->currentIndex();
       int sum=playerlist->mediaCount();
       if(index<sum)
       {
           index++;
       }
       else
       {
           index=0;
       }
       playerlist->setCurrentIndex(index);
       playerObject->play();
}

void MainWindow::on_pushButton_restart_clicked()        //重新播放
{
    if(iPos==0)
    {
        QMessageBox::information(this,"tip","请播放后再点重新播放");
        return;
    }
    playerObject->stop();
    startGifFunc();
    playerObject->play();
}

void MainWindow::on_pushButton_reserch_clicked()    //搜索歌曲
{
    QString str1,str2;
    str1=ui->lineEdit->text();
    str2="http://music.163.com/api/search/get/web?csrf_token=hlpretag=&hlposttag=&s={"+str1+"}&type=1&offset=0&total=true&limit=1";

    //定义一个QNetworkRequest请求对象
    QNetworkRequest request;

    //将请求格式设置给请求对象
    request.setUrl(str2);

    //使用QNetworkManger类对应的api发送get请求并获取响应
    networkAccessManager->get(request);
}

void MainWindow::on_pushButton_voice_clicked()              //静音
{
       bool muteState=playerObject->isMuted();
       playerObject->setMuted(!muteState);

       if(muteState)
       {
           ui->pushButton_voice->setIcon(QIcon(":/images/voice.png"));
       }
       else
       {
           ui->pushButton_voice->setIcon(QIcon(":/images/mute.png"));
       }
}

void MainWindow::on_horizontalSlider_voice_valueChanged(int value)
{
   playerObject->setVolume(value);
}


void MainWindow::on_horizontalSlider_progress_valueChanged(int value)
{
    playerObject->setPosition(value);
}
